package com.chinatsp.onlineapp.ui.news;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;

import com.chinatsp.onlineapp.R;
import com.chinatsp.onlineapp.base.Config;
import com.chinatsp.onlineapp.bean.NewsDetail;
import com.chinatsp.onlineapp.bean.NewsTitle;

import com.chinatsp.onlineapp.listener.DetailNewsListener;
import com.chinatsp.onlineapp.presenter.NewsDetailDao;
import com.chinatsp.onlineapp.presenter.NewsTitleDao;
import com.chinatsp.onlineapp.ui.widget.ProgressHUD;




import tsp.cn.http.interfac.INetResult;

import tsp.cn.http.tools.T;


public class NewsListFragment extends Fragment implements INetResult, OnItemClickListener, OnClickListener,  OnScrollListener {
	ProgressHUD mProgressHUD;
	
	View view;
    ListView lv_title;//新闻标题
    ImageView iv_refresh;//刷新按钮
    int pageNo=1;//当前页
    int p=0;
    int n=10;
    String  channel_id="1";
    DetailNewsListener itemListener;//接口回调 
    
    List<NewsTitle> titleList=new ArrayList<NewsTitle>();//标题的 新闻列表;
    List<NewsDetail> detailList=new ArrayList<NewsDetail>();//详细新闻 列表
    //适配器
    NewsItemAdapter newsItemAdapter;
    
    
    NewsTitleDao titleDao;
    NewsDetailDao detailDao;
    Context context;
   
    public void setItemListener(DetailNewsListener iItemListener) {
        this.itemListener = iItemListener;
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    		Bundle savedInstanceState) {
    	
    	view = inflater.inflate(R.layout.fragment_news_list,null);
        Bundle bundle=getArguments();
        if(bundle!=null){
            channel_id=bundle.getString("channel_id");
        }
        
        initView();
        initData();
        //访问网络获取数据 更新适配
        getNewsID();
        
        
        return view;
    }
    
    

	private void initView() {
        iv_refresh= (ImageView)view.findViewById(R.id.iv_refresh);
        lv_title= (ListView) view.findViewById(R.id.lv_title);
       
        
        iv_refresh.setOnClickListener(this);
        lv_title.setOnItemClickListener(this);
        lv_title.setOnScrollListener(this);
       
    }
    private void initData() {
    	titleList.clear();
        detailList.clear();
        //标题的 列表listview
        newsItemAdapter =new NewsItemAdapter(getActivity());
        newsItemAdapter.setDetailList(detailList);
        lv_title.setAdapter(newsItemAdapter);      
        titleDao=new NewsTitleDao(getActivity(), this);
        detailDao=new NewsDetailDao(getActivity(),this);
        
    }
    
    @Override
    public void onRequestSuccess(int requestCode) {
       
        // 开始更新UI
        this.showProgress(false);
        if(requestCode==Config.CODE_NEWS_TITLE){
        	titleList=titleDao.getList().getResp_data();
        	getNewsDetail();
        }
        if(requestCode==Config.CODE_NEWS_DETAIL){
        	detailList.add(detailDao.getList().getResp_data());
        	newsItemAdapter.setDetailList(detailList);
        	newsItemAdapter.notifyDataSetChanged();
        	//Log.i("cbb",detailList.size()+"");
        }
        
        
    }

   

	

	@Override
    public void onRequestFailed(String errorNo, String errorMessage) {
		 T.showShort(getActivity(), errorMessage);
        // 开始更新UI
        this.showProgress(false);
    }
	/**
     * 无网络连接
     */
    @Override
    public void onNoConnect() {
        showProgress(false);
        T.showShort(getActivity(), "无网络连接");
    }


    /**
     * 加载对话框
     * @param show
     */
    public void showProgress(boolean show) {
        showProgressWithText(show, "加载中...");
    }

    /**
     * 可编辑 提示信息的加载对话框
     * @param show
     * @param message
     */
    public void showProgressWithText(boolean show, String message) {
        if (show) {
            mProgressHUD = ProgressHUD.show(getActivity(), message, true, true, null);
        } else {
            if (mProgressHUD != null) {
                mProgressHUD.dismiss();
            }
        }
    }
    
    
    //刷新新闻 点击事件
	@Override
	public void onClick(View arg0) {
		onRefresh();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		itemListener.itemClick(detailList.get(arg2));
		
	}
	
	//新闻的 当前条数
    private int getP(int pno){
        return (pno-1)*n;
    }
    //获取新闻标题
    private void getNewsID() {
		titleDao.sendUrl(channel_id, getP(pageNo), n);
		
	}
    //获取新闻详细
    private void getNewsDetail() {
		for(NewsTitle title:titleList){
			detailDao.sendUrl(title.getNews_id());
			//detailDao.sendUrl("2");
			
		}
		
	}
    
    /**
     *下拉刷新 重新获取数据
     */
   
    public void onRefresh() {
    	
    	
        pageNo = 1;
        p = getP(pageNo);
        titleList.clear();
        detailList.clear();
        getNewsID();;//重新获取 新闻标题
        
    }

    /**
     * 上拉  加载 更多 数据
     */
    
    public void onLoadMore() {
    	
    	
        pageNo++;// 往下翻页
        p = getP(pageNo);
        getNewsID();
        // 追加下一页的数据
        
    }
    
    //是否到达ListView底部
    boolean isLastRow=false;
    @Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
    	//System.out.println("firstVisibleItem="+firstVisibleItem);
		
		//System.out.println("visibleItemCount="+visibleItemCount);
		//System.out.println("totalItemCount="+totalItemCount);
    	if(firstVisibleItem+visibleItemCount==totalItemCount&&totalItemCount>0){
			//System.out.println("已经到最后一行了");
			isLastRow=true;
		}
		
	}

    @Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
    	//System.out.println("789");
    	if(isLastRow && scrollState==OnScrollListener.SCROLL_STATE_IDLE){
			//执行加载代码
    		
    			onLoadMore();
    		
    		
			isLastRow=false;
		}
		
	}

	@Override
	public void onFinished() {
		showProgress(false);
		
	}
    
}
